<?php
namespace app\api\controller;

use app\home\model\Supply;
use app\home\model\SupplyImg;
use OSS\OssClient;
use OSS\Core\OssException;
use think\facade\Env;

class Upload
{

    /**
     * Undocumented function
     *
     * @return string json
     * 
     * @ oss return result 
     * 
     * [
        "server" => "AliyunOSS"
        "date" => "Fri, 11 Dec 2020 01:24:35 GMT"
        "content-length" => "0"
        "connection" => "keep-alive"
        "x-oss-request-id" => "5FD2CA535369E83938E36F8E"
        "etag" => ""9058930BC5B9ACF81D9E007CE331EE62""
        "x-oss-hash-crc64ecma" => "14007275383979213875"
        "content-md5" => "kFiTC8W5rPgdngB84zHuYg=="
        "x-oss-server-time" => "64"
        "info" => array:27 [
            "url" => "http://jr1test.oss-cn-beijing.aliyuncs.com/test"
            "content_type" => null
            "http_code" => 200
            "header_size" => 310
            "request_size" => 2681
            "filetime" => -1
            "ssl_verify_result" => 0
            "redirect_count" => 0
            "total_time" => 0.196475
            "namelookup_time" => 0.002043
            "connect_time" => 0.072693
            "pretransfer_time" => 0.072844
            "size_upload" => 2260.0
            "size_download" => 0.0
            "speed_download" => 0.0
            "speed_upload" => 11530.0
            "download_content_length" => 0.0
            "upload_content_length" => 2260.0
            "starttransfer_time" => 0.19605
            "redirect_time" => 0.0
            "redirect_url" => ""
            "primary_ip" => "59.110.185.111"
            "certinfo" => []
            "primary_port" => 80
            "local_ip" => "172.17.0.2"
            "local_port" => 57642
            "method" => "PUT"
        ]
                                    BucketName
                                        |   
                                        V
        "oss-request-url" => "http://jr1test.oss-cn-beijing.aliyuncs.com/test"
        "oss-redirects" => 0
        "oss-stringtosign" => """
            PUT
            kFiTC8W5rPgdngB84zHuYg==
            application/octet-stream
            Fri, 11 Dec 2020 01:24:35 GMT
            /jr1test/test
            """
        "oss-requestheaders" => array:7 [
            "Accept-Encoding" => ""
            "Content-Length" => "2260"
            "Content-Md5" => "kFiTC8W5rPgdngB84zHuYg=="
            "Content-Type" => "application/octet-stream"
            "Date" => "Fri, 11 Dec 2020 01:24:35 GMT"
            "Host" => "jr1test.oss-cn-beijing.aliyuncs.com"
            "Authorization" => "OSS LTAI4FzRT6vM9QX1giBon5vT:WH6n0cU5tcawpnodtQL/Y/CnWWA="
        ]
        "body" => ""
        ]
     */
    public function index()
    {
        $bucket = 'jr1test';

        $res = self::initOss();
        if($res['status'] == 200)
        {
            $oss = $res['oss'];
        }else{
            return json($res, $res['status']);
        }

        if (isset($_FILES['file'])){
            $file = $_FILES['file'];
            try {
                $date = date('Ymd');
                $prefix = "upload/$date/";
                $fileName = $prefix.self::getFileInfo($file['name'])['file'];
                $res = $oss->uploadFile($bucket, $fileName, $file['tmp_name'])['info'];
                if ($res['http_code'] == 200){
                    return json(['status'=>200, 'url'=>$res['url'], 'oss_filename'=>$fileName]);
                }else{
                    return json(['status'=>$res['http_code'], 'msg'=>"OSS文件上传错误"], $res['http_code']);
                }
            } catch (OssException $e) {
                return json(['status'=>500, 'msg'=>$e->getMessage()], 500);
            }
        }else{
            return json(['status'=>500, 'msg'=>'unknown file'], 500);
        }
    }

    public function tinymce(){
        $bucket = 'jr1test';

        $res = self::initOss();
        if($res['status'] == 200)
        {
            $oss = $res['oss'];
        }else{
            return json($res, $res['status']);
        }

        if (isset($_FILES['file'])){
            $file = $_FILES['file'];
            try {
                $date = date('Ymd');
                $prefix = "upload/$date/";
                $fileName = $prefix.self::getFileInfo($file['name'])['file'];
                $res = $oss->uploadFile($bucket, $fileName, $file['tmp_name'])['info'];
                if ($res['http_code'] == 200){
                    return json(['location'=>$res['url']]);
                }else{
                    return json(['status'=>$res['http_code'], 'msg'=>"OSS文件上传错误"], $res['http_code']);
                }
            } catch (OssException $e) {
                return json(['status'=>500, 'msg'=>$e->getMessage()], 500);
            }
        }else{
            return json(['status'=>500, 'msg'=>'unknown file'], 500);
        }
    }

    public function supply(){
        $bucket = 'jr1test';

        $res = self::initOss();
        if($res['status'] == 200)
        {
            $oss = $res['oss'];
        }else{
            return json($res, $res['status']);
        }

        $supply_id = $_GET['id'] ;

        if (isset($_FILES['file'])){
            $file = $_FILES['file'];
            try {
                $supply_hash = Supply::find($supply_id)['hash'];
                $prefix = "supply/$supply_hash/";
                $fileName = $prefix.self::getFileInfo($file['name'])['file'];
                $res = $oss->uploadFile($bucket, $fileName, $file['tmp_name'])['info'];
                if ($res['http_code'] == 200){
                    $supply_img = new SupplyImg;
                    $supply_img->save([
                        'provid_id'=>$supply_id,
                        'img'=>$res['url'],
                        'type'=>'supply',
                    ]);
                    return json([
                        'name' => $supply_img->id,
                        'url' => $res['url']
                    ]);
                }else{
                    return json(['status'=>$res['http_code'], 'msg'=>"OSS文件上传错误"], $res['http_code']);
                }
            } catch (OssException $e) {
                return json(['status'=>500, 'msg'=>$e->getMessage()], 500);
            }
        }else{
            return json(['status'=>500, 'msg'=>'unknown file'], 500);
        }
    }

    public static function getOss(){
        return self::initOss()['oss'];
    }

    protected static function initOss(){
        try {
            $ossClient = new OssClient(Env::get('OSS_ACCESS_ID'), Env::get('OSS_ACCESS_KEY'), Env::get('OSS_SERVER_URL'));
            return [
                'status' => 200,
                'oss' => $ossClient,
            ];
        } catch (OssException $e) {
            return json([
                'status'=>500,
                'msg'=>$e,
            ], 500);
        }        
    }
    
    public static function getFileInfo($file){
        $fileName = md5(str_replace(strrchr($file, "."),"",$file).microtime(true));
        return [
            'file_name'=> $fileName,
            'suffix'=> substr(strrchr($file, '.'), 1),
            'file' => $fileName.'.'.substr(strrchr($file, '.'), 1),
        ];
    }

    
}
